<script setup>
import { ref, watch, nextTick, onUnmounted,onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useMusicStore } from '../store/music'

const musicStore = useMusicStore()
const { songUrl, updateCurrentTime, isPlay, volume, playType } = storeToRefs(useMusicStore())

const audio = ref(null)

// 更新歌曲url
watch(() => songUrl.value, () => {
  musicStore.isPlay = true
} , {deep: true})
// 监听播放暂停变化
watch(() => isPlay.value, () => {
  nextTick(() => {
    if(isPlay.value) {
      audio.value.play()
    }else {
      audio.value.pause()
    }
  })
}, {deep: true})
// 更新歌曲当前时间
watch(() => updateCurrentTime.value , () => {
  nextTick(() => {
    audio.value.currentTime = updateCurrentTime.value
    audio.value.play()
  })
}, {deep: true})

watch(() => volume.value, () => {
  nextTick(() => {
    console.log(volume.value)
    audio.value.volume = volume.value * 0.01
  })
},{deep: true})
// 监听是否暂停
const listenPaused = () => {
  musicStore.isPlay = false
}
// 监听是否播放
const listenPlay = () => {
  musicStore.isPlay = true
}
const listenEnded = () => {
  musicStore.isPlay = false
  musicStore.nextSong()
}
// 监听歌曲播放
const listenTimeupdate = () => {
  musicStore.progressVal = (audio.value.currentTime / audio.value.duration) * 100
  musicStore.currentTime = audio.value.currentTime
}
const ondurationchange = () => {
  musicStore.duration = audio.value.duration
}

onMounted(() => {
  nextTick(() => {
    audio.value.volume = volume.value * 0.01
  })
  window.onload = () => {
    listenPaused()
  }
})
onUnmounted(() => {
  musicStore.isPlay = false
})
</script>

<template>
  <audio
    ref="audio"
    id="audio"
    :src="songUrl"
    :loop="playType === 3"
    @play="listenPlay"
    @paused="listenPaused"
    @ended="listenEnded"
    @timeupdate="listenTimeupdate"
    @durationchange="ondurationchange"
  ></audio>
</template>

<style scoped lang="scss">
#audio {
  position: fixed;
  left: 0;
  top: 0;
}
</style>
